/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.bemanager.service;

import com.inspur.edp.cef.designtime.api.IGspCommonField;
import com.inspur.edp.cef.designtime.api.collection.GspAssociationKeyCollection;
import com.inspur.edp.cef.designtime.api.element.GspAssociationKey;
import com.inspur.edp.das.commonmodel.IElementCollection;
import com.inspur.edp.das.commonmodel.IGspCommonObject;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CheckBeChildTableService {

  private static CheckBeChildTableService instance;
  private final String parentID = "parentID";

  /**
   * 校验Be存在子表，且子表parentId 字段非"ParentID"时， 不允许其他表字段为parentId
   *
   * @param containChildObjects be信息
   */
  public void checkChildTable(List<IGspCommonObject> containChildObjects) {
    if (containChildObjects == null) {
      return;
    }
    for (IGspCommonObject iGspCommonObject : containChildObjects) {
      GspAssociationKeyCollection keys = iGspCommonObject.getKeys();
      if (keys.isEmpty()) {
        continue;
      }
      GspAssociationKey key = keys.get(0);
      String parentIdId = key.getSourceElement(); // 获取parentId对应的编号
      examineElements(parentIdId, iGspCommonObject.getContainElements(),
          iGspCommonObject.getName());
      checkChildTable(iGspCommonObject.getContainChildObjects()); // 递归调用校验子表的子表
    }
  }

  private void examineElements(String parentIdId, IElementCollection containElements,
      String tableName) {
    Map<String, String> elementIdToCodeLabelIdMap = containElements.stream().collect(Collectors
        .toMap(IGspCommonField::getID, IGspCommonField::getLabelID));
    String parentIdName = elementIdToCodeLabelIdMap.get(parentIdId);
    if (parentID.equalsIgnoreCase(parentIdName)) {
      // 子表parent 标签为parentID
      return;
    }
    for (String elementLabelName : elementIdToCodeLabelIdMap.values()) {
      if (parentID.equalsIgnoreCase(elementLabelName)) {
        throw new RuntimeException("子节点上不是与上级节点的关联字段不允许将编号设置为parentID,请检查子节点" + tableName);
      }
    }
  }

  public static CheckBeChildTableService getInstance() {
    if (instance == null) {
      instance = new CheckBeChildTableService();
    }
    return instance;
  }
}
